package com.rayson.oneapi.controller;

import com.rayson.oneapi.common.BodyContainer;
import com.rayson.oneapi.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Enumeration;
import java.util.Random;

/**
 * Author: rayson
 * Description:
 * Version: 1.0
 * Date: 2024-09-01 22:02
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {

    @Value("${server.port}")
    private String port;


    @GetMapping("/get")
    public R<String> random(HttpServletRequest request) {
        printHeader(request);
        return R.ok("随机数: " + new Random().nextInt(100) + "", "success");
    }

    @GetMapping("/get/param")
    public R<String> randomParam(String key, HttpServletRequest request) {
        printHeader(request);
        return R.ok("随机数: " + new Random().nextInt(100) + "--->" + key, "success");
    }

    @PostMapping("/post")
    public R<String> post() {
        return R.ok(String.format("现在时间: %s,端口号: %s", LocalDateTime.now(), port), "success");
    }

    @PostMapping("/post/json")
    public R<BodyContainer> postJson(@RequestBody BodyContainer bodyContainer, HttpServletRequest request) {
        printHeader(request);
        return R.ok(bodyContainer, "success");
    }

    @PostMapping("/post/formdata")
    public R<BodyContainer> postFormdata(BodyContainer bodyContainer, HttpServletRequest request) {
        printHeader(request);
        return R.ok(bodyContainer, "success");
    }

    @PutMapping("/put")
    public R<Void> put() {
        return R.ok(null, "put method success");
    }

    private void printHeader(HttpServletRequest request) {
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            String headerValue = request.getHeader(headerName);
            log.info("Header: {} = {}", headerName, headerValue);
        }
    }
}
